/*
 * @Descripttion: Tab的相关操作
 * @version: 1.0
 * @Author: hzj-1510017964@qq.com
 * @Date: 2020-04-21 17:55:50
 * @LastEditors: hzj-1510017964@qq.com
 * @LastEditTime: 2020-05-07 11:03:42
 */
const tab = require('../dao/tabDao')
const testLogin = require('../dao/UserDao')
const utils = require('../utils')
const redisDb = require('../config/redisConfig')
const app = require('../config/appConfig')
const fs = require('fs')
const path = require('path')

getTabList = async (ctx) => {
    try {
        console.log(ctx)
        let list = await tab.getTabList(ctx)
        ctx.body = {
            code: 200,
            success: "ok",
            data: list
        }
    } catch (error) {
        console.log(error, 123)
    }
};

//登录测试
loginTest = async (ctx) => {
    let data = ctx.request.body
    let login = await testLogin.login(data)
    if (login) {
        let payload = {
            uuid: login.uuid,
            id: login.id
        }
        let token = utils.createToken(payload)
        await redisDb.set(app.TOKEN.TOKEN_IN_REDIS_DBNAME, app.REDIS.APP_REDIS_NAME + login.id, token).then(res => {
            if (res) {
                ctx.body = {
                    code: 200,
                    msg: 'success',
                    data: {
                        token: token
                    }
                }
            }
        }).catch(err => {
            console.log(err, 123)
        })
    } else {
        ctx.body = {
            code: "400",
            msg: "error",
            data: "没有该用户"
        }
    }
};

//验证token
verifyToken = async (ctx) => {
    console.log(ctx.token_state)
};


//add user 
addUser = async (ctx) => {
    let data = ctx.request.body
    let queryUser = await testLogin.queryUser({ phone: data.phone })
    if (queryUser) {
        ctx.body = {
            code: "200",
            msg: "error",
            data: '该用户已注册',
            queryUser
        }
    } else {
        let add = await testLogin.addUser(data)
        console.log(JSON.stringify(add))
        if (add) {
            ctx.body = {
                code: "200",
                msg: 'success',
                data: '注册成功'
            }
        } else {
            console.log('失败')
        }
    }
};


uploadFile = async (ctx) => {
    const file = ctx.request.files.file; // 获取上传文件
    // 创建可读流
    const reader = fs.createReadStream(file.path);
    let filePath = path.join(__dirname, '../public/upload/') + `/${file.name}`;
    // 创建可写流
    const upStream = fs.createWriteStream(filePath);
    // 可读流通过管道写入可写流
    let stream = reader.pipe(upStream);
    stream.on('finish', () => {
        
    })
    ctx.body = filePath
}




module.exports = {
    getTabList,
    loginTest,
    verifyToken,
    addUser,
    uploadFile
}